<template>
  <div class="container">
    <!-- 状态筛选模块 -->
    <div class="status-filter" style="padding-bottom: 10px">
      <el-button
          class="button_all"
          :type="data.buttonAll_type"
          @click="selectAll"
      >
        全部订单
      </el-button>
      <el-button
          v-for="(status, key) in statusMap"
          :key="key"
          :type="key === data.selectedStatus ? 'primary' : ''"
          @click="data.selectedStatus = key; select(key)"
      >
        {{ status }}
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
          v-model="data.search_info"
          placeholder="搜索商品名称/订单号"
          class="search-input"
          clearable
      >
        <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template>
      </el-input>
      <el-button type="primary" size="large" class="search-btn">
        搜索订单
      </el-button>
    </div>

    <!-- 订单卡片列表 -->
    <div class="order-list">
      <div
          v-for="(item, index) in data.tableData"
          :key="index"
          class="order-card"
      >
        <!-- 订单头部 -->
        <div class="order-header">
          <span class="order-time">{{ item.createTime }}</span>
          <span class="order-status">
            {{ getStatusName(item.status) }}
          </span>
        </div>

        <!-- 订单主体 -->
        <div class="order-body">
          <!-- 商品图片 -->
          <img
              :src="item.image"
              alt="商品图片"
              class="product-image"
          />
          <!-- 商品信息 -->
          <div class="product-info">
            <div class="product-title">{{ item.title }}</div>
            <div class="product-sellPoint">{{ item.sellPoint }}</div>
            <div class="product-sku">订单号：{{ item.orderNo }}</div>
            <div class="product-price">
              实付款：<span class="price">¥{{ item.payPrice }}</span>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-btns">
            <!-- 发货按钮 -->
            <el-button
                v-if="item.status === 2"
                type="success"
                plain
                @click="deliverOrder(item)"
                class="action-btn"
            >
              发货
            </el-button>

            <!-- 退款按钮 -->
            <el-button
                v-if="item.status === 5"
                type="warning"
                plain
                @click="refundOrder(item)"
                class="action-btn"
            >
              退款
            </el-button>
          </div>

          <!-- 订单尾部 -->
          <div class="order-footer">
            <span class="quantity">数量：{{ item.count }}件</span>
          </div>
        </div>

        <!-- 用户评价信息 -->
        <div v-if="item.comment" class="user-comment">
          <div class="comment-header">
            <span class="comment-title">用户评价：</span>
            <el-rate v-model="item.comment.rating" disabled></el-rate>
          </div>
          <div class="comment-content">{{ item.comment.content }}</div>
          <div class="comment-time">评价时间：{{ item.comment.reviewTime }}</div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="data.currentPage"
            v-model:page-size="data.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total"
            @size-change="load"
            @current-change="load"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive } from "vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";

const data = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  search_info: "",
  tableData: [{}],
  business: JSON.parse(localStorage.getItem("information")) || {},
  selectedStatus: 0,
  buttonAll_type: "default",
});

const statusMap = {
  2: "待发货",
  3: "待收货",
  4: "已完成",
  5: "待退款",
  6: "已退款",
};

const getStatusName = (status) => {
  return statusMap[status] || "未知状态";
};

const load = async () => {
  try {
    const response = await request.get("/order/selectPageByBusiness", {
      params: {
        currentPage: data.currentPage,
        pageSize: data.pageSize,
        id: data.business.businessId,
      },
    });

    if (response.code === 200) {
      data.total = response.data.total;
      data.tableData = response.data.list;

      // 加载每个订单的用户评价
      for (const item of data.tableData) {
        const reviewResponse = await request.get("/review/getByOrderNo", {
          params: {
            orderNo: item.orderNo,
          },
        });

        if (reviewResponse.code === 200) {
          item.comment = reviewResponse.data; // 绑定用户评价
        } else {
          item.comment = null; // 如果没有评价，设置为 null
        }
      }
    }
  } catch (error) {
    console.error("加载订单数据失败:", error);
    ElMessage.error("加载订单数据失败：" + error.message);
  }
};

const selectAll = () => {
  load();
  data.selectedStatus = 0;
  data.buttonAll_type = "primary";
};

const select = async (key) => {
  try {
    const response = await request.get("/order/selectPageByBusinessAndStatus", {
      params: {
        currentPage: data.currentPage,
        pageSize: data.pageSize,
        id: data.business.businessId,
        status: key,
      },
    });

    if (response.code === 200) {
      data.total = response.data.total;
      data.tableData = response.data.list;

      // 加载每个订单的用户评价
      for (const item of data.tableData) {
        const reviewResponse = await request.get("/review/getByOrderNo", {
          params: {
            orderNo: item.orderNo,
          },
        });

        if (reviewResponse.code === 200) {
          item.comment = reviewResponse.data; // 绑定用户评价
        } else {
          item.comment = null; // 如果没有评价，设置为 null
        }
      }
    }
  } catch (error) {
    console.error("加载订单数据失败:", error);
    ElMessage.error("加载订单数据失败：" + error.message);
  }
};

// 发货操作
const deliverOrder = (item) => {
  ElMessageBox.confirm("确认发货", "确认", {type: "success"}).then(() => {
    request.post("/order/deliver", {orderNo: item.orderNo}).then((res) => {
      if (res.code === 200) {
        ElMessage.success("已发货，通知用户收获");
        load();
      } else {
        ElMessage.error("发货失败");
      }
    });
  });
};

// 退款操作
const refundOrder = (item) => {
  ElMessageBox.confirm("确认退款？", "退款", {type: "warning"}).then(() => {
    request.post("/order/refund", {orderNo: item.orderNo}).then((res) => {
      if (res.code === 200) {
        ElMessage.success("退款成功");
        load();
      } else {
        ElMessage.error("退款失败");
      }
    });
  });
};

load();
</script>

<style scoped>
.container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 4px;
}

.search-input {
  flex: 1;
  max-width: 400px;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.order-card {
  background: white;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
  margin-bottom: 16px;
  font-size: 14px;
  color: #666;
}

.order-status {
  font-weight: 500;
}

.order-body {
  display: flex;
  gap: 20px;
  margin-bottom: 16px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  border: 1px solid #eee;
}

.product-info {
  flex: 1;
}

.action-btns {
  display: flex;
  justify-content: space-between;
  gap: 10px;
  min-width: 150px;
  padding-right: 50px;
}

.action-btn {
  padding: 8px 12px;
}

.order-footer {
  padding-top: 12px;
  border-top: 1px solid #eee;
  font-size: 12px;
  color: #999;
}

.user-comment {
  margin-top: 16px;
  padding: 16px;
  background: #f9f9f9;
  border-radius: 4px;
  border: 1px solid #eee;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.comment-title {
  font-size: 14px;
  font-weight: 500;
  margin-right: 10px;
}

.comment-content {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  background: white;
  padding: 16px;
  border-radius: 4px;
}

@media (max-width: 768px) {
  .order-body {
    flex-direction: column;
  }

  .action-btns {
    flex-direction: row;
    justify-content: flex-end;
  }
}
</style>